package com.chandon.juc.threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 只有一个线程的线程池
 *
 * 构建方式:
 *  public static ExecutorService newSingleThreadExecutor() {
 *
 *         return new FinalizableDelegatedExecutorService
 *             (new ThreadPoolExecutor(1, 1,
 *                                     0L, TimeUnit.MILLISECONDS,
 *                                     new LinkedBlockingQueue<Runnable>()));
 *  }
 *
 *  核心时ThreadPoolExecutor构建，只是使用FinalizableDelegatedExecutorService包装了一下：
 *
 *  static class FinalizableDelegatedExecutorService extends DelegatedExecutorService {
 *         FinalizableDelegatedExecutorService(ExecutorService executor) {
 *             super(executor);
 *         }
 *         protected void finalize() {
 *             super.shutdown();
 *         }
 *     }
 *
 *  FinalizableDelegatedExecutorService目的是finalize()，当前线程池被GC回收之前执行shutdown()，但不保证一定会执行。
 *  finalize()执行时是守护线程，无法保证一定可以执行完毕。
 *  当线程池是基于业务构建，一定要手动执行shutdonw()。
 *
 * @author Dong
 */

public class TestSingleThreadExecutor {
	public static void main(String[] args) {

		ExecutorService singleThreadPool = Executors.newSingleThreadExecutor(new NamedThreadFactory("singleThreadPool"));

		singleThreadPool.execute(() -> System.out.println(Thread.currentThread().getName()+" 任务1"));
		singleThreadPool.execute(() -> System.out.println(Thread.currentThread().getName()+" 任务2"));
		singleThreadPool.execute(() -> System.out.println(Thread.currentThread().getName()+" 任务3"));
		singleThreadPool.execute(() -> System.out.println(Thread.currentThread().getName()+" 任务4"));

		singleThreadPool.shutdown();

		// singleThreadPool=null;
		// System.gc();
	}

}
